package cn.zjitc.exam.dao.impl;

import cn.zjitc.exam.dao.ProductDao;
import cn.zjitc.exam.domian.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("productDao")
public class ProductDaoImpl implements ProductDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Product> findAll() {
        String sql = "select * from product";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));
    }

    @Override
    public Product findById(int id) {
        try {
            String sql="select * from product where id=?";
            return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(Product.class),id);
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean update(Product product) {
        String sql="update product set name=?,price=?,description=?,stock=?,creatTime=?,creat_by=?where id=?";
        int update=jdbcTemplate.update(sql,product.getName(),product.getPrice(),product.getDescription(),product.getStock(),product.getCreteTime(),product.getCreate_by(),product.getId());
        return update>0;
    }

    @Override
    public boolean add(Product product) {
        String sql="insert into product(name,price,description,stock,creatTime,create_by) value(?,?,?,?,?)";
        int update=jdbcTemplate.update(sql,product.getName(),product.getPrice(),product.getDescription(),product.getStock(),product.getCreteTime(),product.getCreate_by());
        return update>0;
    }

    @Override
    public boolean delete(int id) {
        String sql="delete from product where id=?";
        int update=jdbcTemplate.update(sql,id);
        return false;
    }

    @Override
    public int getTotalCount() {
        String sql="select count(*) from product";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    @Override
    public List<Product> findByPage(int start, int pageSide) {
        String sql="select * from product limit?,?";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Product.class),start,pageSide);
    }
}
